﻿using Language.Resource;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Filters;
using VisionCloud.Domain.Repository.Implement.Sys;
using VisionCloud.Service.Sys;

namespace VisionCloud.Api.Controllers.Sys
{
    /// <summary>
    /// 设备控制器
    /// </summary>
    [SystemModule("设备管理")]
    [ApiAuthorize(PolicyEnum.RequireRolePermission)]
    [ApiVersion("1.0")]
    [Route("api/sys/[controller]/[Action]")]
    [ApiExplorerSettings(GroupName = "设备管理")]
    public class SysDeviceController : ApiBaseController
    {
        /// <summary>
        /// 设备服务
        /// </summary>
        public SysDeviceService sysDeviceService { get; set; }

        /// <summary>
        /// 用户设备服务
        /// </summary>
        public SysDeviceUserService sysDeviceUserService { get; set; }

        public SysDeviceUnlockService sysDeviceUnlockServer { get; set; }

        /// <summary>
        /// 多语言资源
        /// </summary>
        public IStringLocalizer<ControllerResource> localizer { get; set; }

        /// <summary>
        /// 把设备绑定用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> DevcieFirstSetToUser(RegisterDto request) => await TryCatchAsync(sysDeviceUserService.DevcieSetToUser(request));

        /// <summary>
        /// 获取设备列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> GetDeviceList(SearcheParaSysDevicePage request) => await TryCatchAsync(sysDeviceService.GetList(request));

        /// <summary>
        /// 批量删除设备
        /// </summary>
        /// <param name="deviceGuidList"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> DeleteDevices(Guid[] deviceGuidList) => await TryCatchAsync(sysDeviceService.DeletesAsync(deviceGuidList));

        /// <summary>
        /// 根据扫描仪序列号获取设备信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> GetDeviceByScannerSN(DeviceCondtion query) => await TryCatchAsync(sysDeviceService.GetDeviceByScannerSN(query));

        /// <summary>
        /// 更新设备
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> UpdateDevice(SysDevice deviceInfo) => await TryCatchAsync(sysDeviceService.UpdateDevice(deviceInfo));

        /// <summary>
        /// 更新设备版本信息
        /// </summary>
        /// <param name="versionDto"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        [SwaggerResponse(0, "更新设备版本信息", typeof(bool))]
        public async Task<ApiResult> UpdateSoftVersion(SysDeviceVersionDto versionDto)
        { return await sysDeviceService.UpdateSoftVersion(versionDto); }

        /// <summary>
        /// 更新设备
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> AddDevice(SysDevice deviceInfo) => await TryCatchAsync(sysDeviceService.AddDevice(deviceInfo));

        /// <summary>
        /// 分配设备
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        [ApiAuthorize(PolicyEnum.RequireCompanyManager)]
        public async Task<ApiResult> AssignDeviceUser(AssignSysDeviceDto deviceInfo) => await TryCatchAsync(sysDeviceService.AssignDeviceUser(deviceInfo));

        /// <summary>
        /// 批量分配设备，如果之前已分配的设备未被选中要删除
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        [ApiAuthorize(PolicyEnum.RequireCompanyManager)]
        public async Task<ApiResult> AssignDeviceUserBatch(AssignSysDeviceDto deviceInfo) => await TryCatchAsync(sysDeviceService.AssignDeviceUserBatch(deviceInfo));

        /// <summary>
        /// 解绑设备
        /// </summary>
        /// <param name="deviceInfo"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        [ApiAuthorize(PolicyEnum.RequireCompanyManager)]
        public async Task<ApiResult> DeleteDeviceUser(AssignSysDeviceDto deviceInfo) => await TryCatchAsync(sysDeviceService.DeleteDeviceUser(deviceInfo));

        /// <summary>
        /// 设备excel文档导入
        /// </summary>
        /// <param name="formCollection">excel导入dto</param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> ImportExcelToDevice(IFormCollection formCollection)
        {
            if (formCollection.Files?.Count > 0)
            {
                return await TryCatchAsync(sysDeviceService.ImportExcelFile(formCollection.Files[0]));
            }
            else
            {
                return new ApiResult(Domain.Common.AjaxCode.Error, localizer["YB0007"].Value);
            }
        }

        /// <summary>
        /// 设备excel文件导出
        /// </summary>
        /// <param name="searcheParaMsDevicePage"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> ExportDeviceToExcel(SearcheParaSysDevicePage searcheParaMsDevicePage)
        {
            try
            {
                searcheParaMsDevicePage.PageSize = int.MaxValue;
                searcheParaMsDevicePage.DeviceNumber = searcheParaMsDevicePage.DeviceDateOfProduction_End = searcheParaMsDevicePage.DeviceDateOfProduction_begin = searcheParaMsDevicePage.CustomerCompanyName = string.Empty;
                var result = await sysDeviceService.GetList(searcheParaMsDevicePage);
                if (result.Total > 0)
                {
                    var DataList = (result.PageData as List<SysDeviceDto>);
                    if (searcheParaMsDevicePage.Select != null)
                    {
                        DataList = DataList.Where(p => searcheParaMsDevicePage.Select.Contains(p.DeviceGuid.ToString())).ToList();
                    }
                    return ApiResult.Success().SetData(await sysDeviceService.ExportExcelFile(DataList));
                }
                else
                {
                    return ApiResult.Error(localizer["YB0035"].Value);
                }
            }
            catch (Exception ex)
            {
                return ApiResult.Error(ex.Message);
            }
        }

        /// <summary>
        /// 解锁控评
        /// </summary>
        /// <param name="unlock"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> DeviceUnlock(SysDeviceUnlockDto unlock) => await TryCatchAsync(sysDeviceUnlockServer.UnlockDevice(unlock));

        /// <summary>
        /// 作者：黄钧航
        /// 提供FMS-获取所有已激活设备
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> GetAllActivedDevices()
        {
            return await TryCatchAsync(sysDeviceService.GetAllActivedDevices());
        }

        /// <summary>
        /// 查询公司的所有加密狗设备
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> GetOrgDevices([FromBody] SysOrgIdDto model)
        {
            return await TryCatchAsync(sysDeviceService.GetOrgAllActivedDevices(model.OrgId.ToString()));
        }

        /// <summary>
        /// 根据加密狗编号查询加密狗设备（此接口提供给Surface端使用）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost, SwaggerOperation(Tags = new[] { "设备管理" })]
        public async Task<ApiResult> GetOrgDeviceDetail([FromBody] UsbKeyNoDto model)
        {
            return await TryCatchAsync(sysDeviceService.GetOrgDeviceDetail(model?.UsbKeyNo));
        }
    }
}